#include "treerender.h"
#include <GL/glu.h>
#define PI 3.14
using namespace std;
TreeRender::TreeRender(){
    mQuadric = gluNewQuadric();
    gluQuadricNormals(mQuadric, GL_SMOOTH);					// Generate Smooth Normals For The Quad
    gluQuadricTexture(mQuadric, GL_TRUE);
}
void TreeRender::drawTree(TreeGen *treegen){
//TODO: fill this in before thursday
    recurDraw(treegen->treeRoot);
    glDisable(GL_LIGHTING);
    glColor3f(1,0,0);
    glLineWidth(5);
    glMatrixMode(GL_MODELVIEW);
    glBegin(GL_LINES);
        glVertex3f(0,0,0);
        glVertex3f(0,0,20);
    glEnd();
    glColor3f(0,1,0);
    glBegin(GL_LINES);
        glVertex3f(0,0,0);
        glVertex3f(0,20,0);
    glEnd();
    glColor3f(0,0,1);
    glBegin(GL_LINES);
        glVertex3f(0,0,0);
        glVertex3f(20,0,0);
    glEnd();
    //drawBranch(float3(5,3,0), float3(5,9,0),PI/2.0,0,6,2);
}

void TreeRender::recurDraw(Bud *b){
    //drawBranch(b->start,b->end,b->theta - PI/2.0, 0 ,b->length,b->diameter/2.0);
    drawBranch(b->start,b->end,b->phi,b->theta,b->length,b->diameter/2.0);
    if(b->aux)
        recurDraw(b->aux);
    if(b->term)
        recurDraw(b->term);
}

void TreeRender::animateTree(){}
//TODO: for shadow propagation, create a large grid first, a bud is stationary store it in as you go so for shadow propagation it's just a look up
void TreeRender::drawBranch(float3 start, float3 end, float phi, float theta, float length, float radius){

    phi *= 180.0/PI;
    theta *= 180.0/PI;
    glColor3f(1,1,1);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glPushMatrix();
    glTranslatef(start.x, start.y, start.z);
    glRotatef(phi,0,0,1);
    glRotatef(theta,0, 1, 0);
    glRotatef(-90, 1, 0, 0);
    //note cylinder might be rotated
    gluCylinder(mQuadric, radius, radius, length, 15, 5);//slices/stacks based on radius and length?
    glPopMatrix();

    glPushMatrix();
    glTranslatef(start.x, start.y, start.z);
    glRotatef(-90, 1, 0, 0);
    gluSphere(mQuadric, radius, 15, 15);
    glPopMatrix();

    glPushMatrix();
    glTranslatef(end.x, end.y, end.z);
     glRotatef(-90, 1, 0, 0);
    gluSphere(mQuadric, radius, 15, 15);
    glPopMatrix();
}
//use shadow maps for shadowing
void TreeRender::drawLeaf(){}
void TreeRender::drawBud(Bud * b){
    drawBranch(b->start, b->end, b->phi, b->theta, b->length, b->diameter);
}
void TreeRender::drawFlower(){}
//Note that if we use dome caps for the internodes the min length of a branch coming off of it must
//be the internodes radius (or it won't be seen), could be remedied by using a flatter cap, sacrificing some smoothness
//Don't think it'll be a big issue though
